import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { _HttpClient, SettingsService, User } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-sys-user-edit',
  templateUrl: './edit.component.html'
})
export class SysUserEditComponent implements OnInit {
  record: any = {};
  i: any;
  passwordVisible = false;
  password?: string;
  validateForm: FormGroup;
  companyDefault: any = '';
  controlsConfig = {
    ID: [null, null],
    username: ['', [Validators.required]],
    nickname: ['', []],
    status: [1, []],
    password: ['', [Validators.required]],
    company_id: ['', [Validators.required]],
    ex_company_ids: ['', []]
  };
  companies = [];

  constructor(
    private modal: NzModalRef,
    private msgSrv: NzMessageService,
    public http: _HttpClient,
    private fb: FormBuilder,
    private settingService: SettingsService
  ) {
    if (this.settingService.user.company_id != 0) {
      this.companyDefault = this.settingService.user.company_id;
    }
    this.loadDataFromServer();
    this.controlsConfig.company_id = [this.companyDefault, [Validators.required]];
    this.validateForm = this.fb.group(this.controlsConfig);
  }

  ngOnInit(): void {
    if (this.record.ID > 0) {
      this.http.get(`api/user/${this.record.ID}`).subscribe(res => {
        //单选变为多选
        res.data.ex_company_ids = `${res.data.ex_company_ids}`.split(',').map(function (num) {
          return parseInt(num);
        });
        this.validateForm.patchValue(res.data);
        this.i = res.data;
      });
    }
  }

  loadDataFromServer() {
    this.http.get(`api/company_map`).subscribe(res => {
      this.companies = res.data;
    });
  }

  save(value: any): void {
    let ids = [];
    if (value.ex_company_ids && value.ex_company_ids.length > 0) {
      for (let id of value.ex_company_ids) {
        id && ids.push(id);
      }
    }
    value.ex_company_ids = ids.join(',');
    if (value.ID) {
      this.http.put(`api/user/${value.ID}`, value).subscribe(res => {
        if (res.err_code != 0) {
          this.msgSrv.error(res.msg);
          return;
        }
        this.msgSrv.success(res.msg);
        this.modal.close(true);
      });
    } else {
      this.http.post(`api/user`, value).subscribe(res => {
        if (res.err_code != 0) {
          this.msgSrv.error(res.msg);
          return;
        }
        this.msgSrv.success(res.msg);
        this.modal.close(true);
      });
    }
  }

  close(): void {
    this.modal.destroy();
  }
}
